package com.katydid.web.controller;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.katydid.NoteManager;
import com.katydid.NoteManagerImpl;
import com.katydid.NoteManagerRemote;
import com.katydid.domain.Category;

@ManagedBean
// @Named
@ViewScoped
// @RequestScoped
public class CategoryController implements Serializable {

	private boolean localMode = true;

	private Long categoryId; // for editing

	private Category category;

	private List<Category> categoryList;

	@EJB
	private NoteManagerRemote noteManagerRemote;  // remote

	@EJB
	private NoteManager noteManager;  // local
	
	@EJB
	private NoteManagerImpl noteManagerImpl;  //localbean, no interface view

	public Category getCategory() {
		if (category == null) {
			category = new Category();
		}
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public Long getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(Long categoryId) {
		this.categoryId = categoryId;
	}

	public List<Category> getCategoryList() {
		return categoryList;
	}

	public void setCategoryList(List<Category> categoryList) {
		this.categoryList = categoryList;
	}

	public String addCategory() {
		noteManager.addCategory(category);
		System.out.println("Save " + category.getName() + "  " + category.getDirectory());
		return "newCategory.faces";
	}

	// fetch to display on list view
	@PostConstruct
	public void findAllCategories() {
		if (categoryList == null) {
			if (localMode) {
				categoryList = noteManager.getAllCategories();
			} else {
				categoryList = noteManagerRemote.getAllCategories();
			}
			System.out.println("Find " + categoryList.size() + " categories.");
		}
	}

	public void findCategory() {
		category = noteManager.getCategory(categoryId);
	}

	public String updateCategory() {
		if (localMode) {
			noteManager.updateCategory(category);
		} else {
			noteManagerRemote.updateCategory(category);
		}
		System.out.println("Update " + category.getId() + " " + category.getName() + "  " + category.getDirectory());
		return "listCategory.faces";
	}

	public String deleteCategory() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		long catId = Long.valueOf(map.get("categoryId"));
		Category cat = noteManager.getCategory(catId);
		System.out.println("Delete " + cat.getId() + " " + cat.getName() + "  " + cat.getDirectory());

		noteManager.removeCategory(cat);

		return "listCategory.faces";
	}

}
